/*
* YSI Common
* http://www.yousendit.com/
*
*
*
* Date:
* Revision:
*/

var YSI = YSI || {};
var login_dialog;
//i18n vars
document.write(unescape("%3Cscript src='"+ "/lib/smartling/i18n_vars.js'  type='text/javascript'%3E%3C/script%3E"));
// OnLoad call common_init()
(function()
{
	var ispList = [];
	$(document).ready( function(){
            common_init();
	});

})(jQuery);

function common_init() {

	/* Header */

	// Attach mouse events to header tabs
	$('#nav-menu li').each(function()
	{
		$(this).mouseover(function() {
			$(this).addClass('hd-hover');
		});

		$(this).mouseout(function() {
			$(this).removeClass('hd-hover');
		});
	});

	var hd_select = 'none';
	if($("#ysi_hd_select").length > 0) {
		hd_select = $('#ysi_hd_select').val();
	}

	if(hd_select != '' && $('#'+hd_select).length > 0) {
		$('#'+hd_select).addClass('selected');
	}
	setDialogDefaults();

	var qtipDefaults = {};
	setQtipDefaults();
	
	// Login dialog
	login_dialog = $("#basic-modal-content").dialog({
		height: 'auto',
		autoOpen:false,
		resizable:false,
		width: $(".smartling-fr").length ? 710 : 660,
		modal:true,
		open: function (event, ui) {			
			if(typeof login_dialog.defaultEmail != "undefined") {
				$('#ysi_exists_msg').show();
				$('#ysi_su_email').val(login_dialog.defaultEmail);
				$('#ysi_su_pwd').focus();
			}
			$("#ui-dialog-title-basic-modal-content").parent().hide();
			$("#ysi_verify_msg").hide();
            if($(".smartling-fr").length)
    	        $("#ui-dialog-title-basic-modal-content").parents('.ui-dialog').css('padding','0px').height(293);
            else
	            $("#ui-dialog-title-basic-modal-content").parents('.ui-dialog').css('padding','0px').height(283);
			$("#signupLoginFormDiv").parent().css("padding-top","15px");
			if( $.trim($("#ysi_su_email").val()) == '' ) {
				$("#ysi_su_email").focus();
			}
			else {
				$("#ysi_su_pwd").focus();
			}
			var tmdData = {
			    pagename:getPageName(),
			    modalname:"existing_user_dialog",
			    accttype:getCookieAcctType(),
			    triggertype:'o'
			}
			if (typeof psModalData != 'undefined') {
				tmdData.sid = psModalData.sid;
				tmdData.cid = psModalData.cid;
			}

			trackmodaldetailed (tmdData);
			//trackmodal (getPageName ()+":"+getCookieAcctType(), "existing_user_dialog");
		}
	});

	$('#hd_nav_login, #ysi_lg').click(function() {
		$("#ysi_exists_msg, #ysi_verify_msg").hide();
		
		$("#ysi_exist_id_sender").hide();			
		$("#basic-modal-content .login_box_wrapper .login-header-title, .oauth_social_box_wrapper .login-header-title").show();
		$(".login_box_wrapper").css("padding-top","30px"); 
		$(".oauth_social_box, .oauth_divide_wrapper").css("margin-top","30px");

		login_dialog.dialog('open');
		$(".ui-dialog").height(280);
		return false;
	});

	// Existing user login buttons
	$("#basic-modal-content-cancel").click(function() {
		$('#ysi_su_pwd').val('');
		login_dialog.dialog('close');
		if(typeof login_dialog.customizedCancel == 'function') {
			login_dialog.customizedCancel();
			return false;
		}
	});

	$('#ysi_logout').click(function() {
		doLogout();
	});

	// Client-side error dialog
	$("#ysi_dlg_error").dialog({
		width: 510,
		autoOpen: false,
		resizable: false,
		modal: true,
		open: function (event, ui) {
			var errorDialogTitle = $("#ui-dialog-title-ysi_dlg_error");
			errorDialogTitle.siblings('.ui-dialog-titlebar-close').hide();
			errorDialogTitle.parent().show().css('margin','20px 20px 10px 20px').siblings().css('padding','0px 20px 0px 20px');
			errorDialogTitle.parent().parent().show().css('margin','20px 20px 10px 20px');
			var tmdData = {
			    pagename:getPageName(),
			    modalname:"phi_error_dialog",
			    accttype:getCookieAcctType(),
			    triggertype:'o'
			}
			trackmodaldetailed(tmdData);
		},
		close: function(event, ui) {
			var el = $('#ysi_dlg_error');
			if(typeof el.data('callback') == 'undefined') return;
			if(typeof el.data('param') == 'undefined') {
				el.data('callback')();
			} else {
				el.data('callback')(el.data('param'));
				el.removeData('param');
			}
			el.removeData('callback');
		}
	});

	// Client-side error dialog button handler
	$("#ysi_btn_error").click(function() {
		$("#ysi_dlg_error").dialog("close");
	});

	loginValidate();
}

function getOmnitureParams() {
	var omnitureData = {category: 'SUB', event1: 42, event2: 43, event3: 41};
	var acctAry = $.cookie ("acct").split(",");
	if(acctAry.length > 6) {
		switch(acctAry[3]) {
			case 'PAID':
			if(acctAry[5] == 1) {
				omnitureData.category = 'TRIAL';
				omnitureData.event1 = 44;
        omnitureData.event2 = 45;
        omnitureData.event3 = 49;
			}
			break;
			case 'PROMO':
			case 'TRIAL':
			omnitureData.category = 'TRIAL';
			omnitureData.event1 = 44;
      omnitureData.event2 = 45;
      omnitureData.event3 = 49;
			break;
		}
	}
	return omnitureData;
}

function areCookiesEnabled(){
	//supported in modern browsers
    var cookieEnabled=(navigator.cookieEnabled)? true : false
    
    //older versions of IE (before IE6) and mobile browsers that don't support navigator.cookieEnabled
    if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
    	//create a test cookie
        document.cookie="testcookie";
        //check if that cookie exists
        cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false;
        //expire the test cookie
	    document.cookie = 'testcookie=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    return cookieEnabled;
}

function getCookieAquisitionType() {
	if ($.cookie("acct")){
		var acctAry = $.cookie ("acct").split(",");
		if(acctAry.length > 3) {
			return acctAry[3];
		}
	}
	return null;
}

function getCookieAcctType () {
	var acctType;
	if ($.cookie ("acct")) {
		var splitarray = $.cookie("acct").split(",");
		return splitarray[0];
	} else {
		return "GST";
	}
}

function getCookieAcctAry() {
	var acctAry = [];
	if($.cookie("acct")) {
		var acctAry = $.cookie("acct").split(",");
	}
	return acctAry;
}

function getPageName () {
	var omniturepagename = $.trim($('#omniturePageName').val());
	if (omniturepagename) {
		return omniturepagename;
	} else {
		return "http://"+window.location.hostname+window.location.pathname;
	}
}


function doLogout() {
	var options = {domain: 'hightail.com', path:'/'};

	$.cookie('Ysi_session_id', null, options);
	$.cookie('auth', null, options);
	$.cookie('api_at', null, options);
	$.cookie('acct', null, options);
	$.cookie('uname', null, options);
	$.cookie('oauth_nonce', null, options);	
	$.cookie('fresh_login', null, options);	
	$.cookie('lithiumSSO:hightail', null, options);	
	$.cookie('taf_task', null, options);	
    $.cookie('taf_task_to_flash', null, options);	
    $.cookie('taf_badge_to_flash', null, options);	
    $.cookie('source_id', null, options);	
    $.cookie('marketplaceUrl', null, options);	
    $.cookie('uid', null, options);	
    $.cookie('uaid', null, options);	
    $.cookie('tauOptInBarDismissed', null);
    $.cookie('ADMIN_MENU_OPEN', null);
    if(1 != $.cookie('rememberEmail')) $.cookie('emailAddress', null, options);
    
	try {
		var oauthJson = $.JSON.decode($.cookie('oauth'));
		oauthJson.user_registed = '';
		oauthJson.user_login = false;
		oauthJson = $.JSON.encode(oauthJson);

 		options = {domain: 'hightail.com', path:'/'};
		$.cookie('oauth', oauthJson, options);
	} catch(e) {}
	var url;
	if(YSI && YSI.LogoutInterstitial) {
		url = YSI.LogoutInterstitial.getLogoutUrl();
	} else {
		url = "/login";
	}
	window.location.replace(url);
}

function setDialogDefaults() {
	$.extend($.ui.dialog.defaults, {
		modal: true,
		bgiframe: true,
		resizable: false,
		closeOnEscape: true,
		autoOpen: false,
		hide: 'slide'
	});

}

function setQtipDefaults() {
	qtipDefaults= {
		show: 'mouseover',
		hide: { fixed: true},
		style: {
			'font-family': 'sans-serif',
			'font-size':'11px',
			'background': 'none repeat scroll 0 0 #fff',
			width:350,
			paddingTop:0,
			paddingRight:0,
			paddingBottom:0,
			paddingLeft:0,
			border: {width:1,color:'#000'}
		},
		position: {
			corner: {
				target: 'rightMiddle',
				tooltip: 'leftMiddle'
			}
		}
	};
}

function loginValidate() {
	if( $("#ysi_hd_login").length > 0 ) {

		$("#ysi_hd_login").validate({
			errorElement: "em",
			errorPlacement: function(error, element) {
				$(element).siblings('em').remove();
				error.insertAfter(element);
			},
			highlight : function(element, errorClass) {
				$(element).css('border', '1px solid #B41E27');
				$('label[for='+$(element).attr('id')+']').addClass('error-red');
			},
			unhighlight : function(element, errorClass) {
				$(element).css('border', '1px solid #CCCCCC');
				$('label[for='+$(element).attr('id')+']').removeClass('error-red');
			},
			rules: {
				ysi_su_email : {
					required: true,
					email: {
						depends: function(){
							if( $(this).val().match(/^\s/) ||  $(this).val().match(/\s$/) ) $("#ysi_su_email").val($.trim($(this).val()));
							return true;
						}
					},
					maxlength: 100
				},
				ysi_su_pwd : {
					required: true,
					minlength: 4
				}
			},
			messages: {
				ysi_su_email : {
					required: "<br/>" + i18nvars.validate_email,
					email: "<br />" + i18nvars.validate_invalid_email,
					maxlength: "<br />" + i18nvars.validate_long_email
				},
				ysi_su_pwd : {
					required: "<br/>" + i18nvars.validate_req_password,
					minlength: "<br />" + i18nvars.validate_invalid_password
				}
			}
		});
	}
}

function showError(title, errBody, callback, param){
	if (title == '' || title == null) {
		title = 'Error';
	} else {
		$('#ysi_dlg_error').dialog('option', 'title', title);
	}

	if (errBody == '' || errBody == null) {
		errBody = "An error has occurred";
	} else {
		$("#error-body").html(errBody);
	}

	var el = $('#ysi_dlg_error');
	if(typeof callback != 'undefined') {
		el.data('callback', callback);
		if(typeof param != 'undefined') {
			el.data('param',param);
		}
	}

	el.dialog('open');
}

function getUrlParam(param_name) {
	var regex = new RegExp('[\\?&]' + param_name + '=([^&#]*)');
	var results = regex.exec( window.location.href );
	return results ? results[1] : null;
}

function isInISP(userEmail) {
	var userDomain = userEmail.split('@');
	if(ispList.length > 0) {
		return ($.inArray(userDomain[1].toLowerCase(), ispList) != -1) ? true : false;
	}
	return false;
}

function gMigrateUserV3toV2(redirectUrl) {
	var acctAry = getCookieAcctAry();
	if(acctAry.length > 1) {
		if(acctAry[1] != 1) {
			$.post('/lite?phi_action=app/getUserStatus', null, function(retDat) {
				if(typeof retDat == 'object' && retDat.acctType != 'GST' && !retDat.emailVerified) {
					window.location = '/validateEmail';
				} else {
					gMigrateUserV3toV2(redirectUrl);
				}
			}, 'json');
			return false;
		} else {
			$.post('/lite?phi_action=app/migrateUserV3toV2', null,
			function(data){
				if(data == 'true') {
					var trans_auth = $.cookie('trans_auth');
					var opt = {expires:0, domain:'hightail.com'};
					var dt = new Date();
					$.cookie('at', trans_auth, opt);
					$.cookie('buss', trans_auth + '&' + dt.getTime(), opt);
					window.location = redirectUrl;
				} else {
					showError('Migration Failed','An error occurred when attempting to migrate user.<br/><br/>Error code: 1060');
				}
			});
		}
	} else {
		window.location = redirectUrl;
	}
	return false;
}

function getQueryStringParams() {
	var params = {};
	var queryString = window.location.search.substring(1).split('&');
	for(var i in queryString) {
		var pair = queryString[i].split('=');
		if(pair.length < 2) {
			params[pair[0]] = pair[1];
		} else {
			params[pair[0]] = pair[1];
		}
	}
	return params;
}

function getValueByKey(paramsAry, searchKey) {
	for(var k in paramsAry) {
		if(k == searchKey) return paramsAry[k];
	}
	return null;
}

function isValidWLBL(emails) {
	var validWLBL = true;
	var emailsArr = [];
	var invalidDomains = '';

	if (typeof wl != 'undefined' && wl != '') {
		wlArr = wl.breakStringByDelim([',']);
	} else if (typeof bl != 'undefined' && bl != '') {
		blArr = bl.breakStringByDelim([',']);
	} else {
		return '';
	}

	// Special case for Dropbox since we're checking the From field for WL BL data
	if (typeof dropboxOwnerEmail != 'undefined' && dropboxOwnerEmail != ''){
		emailsArr = dropboxOwnerEmail.breakStringByDelim([',',';']);
    } else {
        emailsArr = emails.breakStringByDelim([',',';']);
    }


	for(var i=0; i<emailsArr.length;i++) {
		if(emailsArr[i] == '') {continue;}
		var trimmed = $.trim(emailsArr[i]);
		var tmp = trimmed.split("@");
		var emailDomain = tmp[tmp.length - 1];
		if ('undefined' != typeof bl && bl) {
			validBL = false;
			for (var j=0; j<blArr.length; j++) {
				if (emailDomain.toLowerCase() == blArr[j].toLowerCase()) {
					if (invalidDomains == '')
						invalidDomains = emailDomain;
					else
						invalidDomains += "," + emailDomain;
					break;
				}
			}
		} else {
			validWL = false;
			for (var j=0; j<wlArr.length; j++) {
				if (emailDomain.toLowerCase() == wlArr[j].toLowerCase()) {
					validWL = true;
					break;
				}
			}
			if (!validWL) {
				if (invalidDomains == '')
					invalidDomains = emailDomain;
				else if (invalidDomains.indexOf(emailDomain) == -1)
					invalidDomains += "," + emailDomain;
			}
		}
	}

	return invalidDomains;
}

function isDomainInList(domain, list) {
  var matches = [];

  $.each(domain, function(i, dm) {
    $.each(list, function(j, ls) {
      if (dm.match(new RegExp('\\b'+ls+'$', 'i'))) {
        matches.push(dm);
      }
    });
  });

  return matches;
}

function isDomainBlacklisted(domain, list) {
  if(typeof(domain) == 'string') {
    domain = domain.split(',');
  }

  var matches = isDomainInList(domain, list);

  // all it takes is 1 match to be blacklisted
  return {'success': matches.length > 0, 'matches': matches};
}

function isDomainWhitelisted(domain, list) {
  if(typeof(domain) == 'string') {
    domain = domain.split(',');
  }

  var matches = isDomainInList(domain, list);

  // all domains must pass to return true
  return {'success': matches.toString() == domain.toString(), 'matches': matches};
}

function ellipsis(str, maxlen) {
  if (str.length > maxlen) {
    return str.substr(0, maxlen - 11) + '...' + str.substr(str.length-8, str.length);
  }
  return str;
}

/* fitText([
    {selector: "#downloadTitleSender span",width: 400},
    {selector: "#downlaodMsgSender span",width: 360},
    {selector: ".filenameList span", width: 400}
   ], rightChar)
   rightChar: characters keep on right, 3 means: xxxx...xxx, 0 means: xxxx..., default keep 7 
    */
function fitText(ary, rightChar) {
	if('undefined' == typeof rightChar) rightChar = 7;
  var cnt, i;
  for (i in ary) {
    cnt = 0;
    $(ary[i].selector).each(function() {
      var el, part1, part2, txt;
      el = $(this);
      if (el.width() > ary[i].px) {
        txt = el.text();
        el.attr("title", txt);
        cnt = txt.length;
        if (cnt > rightChar) {
          part2 = rightChar ? txt.slice(-rightChar) : '';
          cnt -= rightChar;
	        while (el.width() > ary[i].px) {
	          cnt--;
	          part1 = txt.substr(0, cnt);
	          el.text(part1 + "..." + part2);
	        }
        }
      }
    });
  }
}

// act: show/hide, parentSelector: jquery selector for parent container
function spinningWheel(act, parentSelector) {
	if(!parentSelector) parentSelector = 'body';
	if(act == 'show') {
		$('<div class="spinningWheel"></div>').appendTo(parentSelector);
	} else {
		$('.spinningWheel').remove();
	}
}

/*
   This function shows a colored drop-down block over the navigation.
   To use:
      showGlobalMessage('type','This is the message text', [duration integer]);

      The first param 'type' can be one of three values 'error', 'success', 'warning'.  Note that error and warning use the same color.
*/

function showGlobalMessage(msgType, msg, duration) {
  var validTypes = ['error', 'warning', 'success'];
  if($.inArray(msgType, validTypes) < 0) msgType = validTypes[0];
  var removeTypes = $.grep(validTypes, function(tp) {
    return tp != msgType;
  });
  if (typeof YSI.gMsgTimeout != 'undefined') {
    clearTimeout(YSI.gMsgTimeout);
  }
  var gm = $('.globalTopMessage');
  if(gm.length < 1) {
    $('<div class="globalTopMessage"><div class="innerContainer"><div class="msg"></div><div class="globalTopClose"></div></div></div>').appendTo('body');
    gm = $('.globalTopMessage');
  }
  if($.cookie('Ysi_session_id')) gm.addClass('loggedIn');
  gm.removeClass(removeTypes.join(' ')).addClass(msgType);
  gm.find('.msg').html(msg);
  gm.animate({ 'top': '0px' }, 250);
  $(".globalTopClose").off().on('click', function() {
    if (typeof YSI.gMsgTimeout != 'undefined') {
      clearTimeout(YSI.gMsgTimeout);
    }
    $(".globalTopMessage").animate({'top': '-' + $(".globalTopMessage").height() + 'px'}, 250);
  });
  if (typeof duration !='undefined') {
    YSI.gMsgTimeout = setTimeout(function() {$(".globalTopClose").click();}, duration);
  }
}

function addFieldError(elem, msg) {
  var parentField = elem.addClass('warning').parent();
  if(msg) {
    var fixMe = parentField.find('.fix-me');
    if(!fixMe.length) {
      parentField.append('<div class="fix-me"></div>');
      fixMe = parentField.children('.fix-me');
    }
    fixMe.html('<div class="tip">' + msg + '<div class="arrow"></div><div class="extraSpace"></div></div>');
  }
}

function removeFieldError(elem) {
  if('undefined' == typeof elem) {
    $('.fix-me').remove();
  } else {
    elem.parents().children('.fix-me').remove();
    elem.removeClass('warning');
  }
}